#include "alarmitemwidget.h"
#include <QtConcurrent>

AlarmItemWidget::AlarmItemWidget(QWidget *parent) : QWidget(parent)
{
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(10, 5, 10, 5);

    m_iconLabel = new QLabel(this);
    m_iconLabel->setFixedSize(32, 32);
    m_iconLabel->setScaledContents(true);

    m_contentLabel = new QLabel(this);
    m_contentLabel->setWordWrap(true);
    m_contentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    layout->addWidget(m_iconLabel);
    layout->addWidget(m_contentLabel, 1);

    m_styleTemplate =
        "QLabel {"
        "   padding: 5px;"
        "   border-radius: 3px;"
        "   color: %1;"
        "   background-color: %2;"
        "   border: 1px solid %3;"
        "}";
}

void AlarmItemWidget::updateContent(const AlarmData &data)
{
    QString html = QString("<b>%1</b><br>"
                          "<font color='#666'>原因：%2</font><br>"
                          "<font color='#777'>建议：%3</font><br>"
                          "<font color='#888'>时间：%4</font>")
                   .arg(data.message).arg(data.reason).arg(data.solution).arg(data.timestamp);

    m_contentLabel->setText(html);

    // 异步加载图片
    if(!data.iconPath.isEmpty()) {
        QtConcurrent::run([=]{
            QPixmap pix(data.iconPath);
            if(pix.isNull()) return;
            pix = pix.scaled(32, 32, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            QMetaObject::invokeMethod(this, [=]{
                m_iconLabel->setPixmap(pix);
            }, Qt::QueuedConnection);
        });
    }

    // 设置样式
    applyStyle(data.level);
}

void AlarmItemWidget::applyStyle(int level)
{
    QString color, bgColor, borderColor;

    switch(level) {
    case 0:  // 普通
        color = "#333"; bgColor = "#f0f0f0"; borderColor = "#ccc";
        break;
    case 1:  // 警告
        color = "#8a6d3b"; bgColor = "#fcf8e3"; borderColor = "#faebcc";
        break;
    case 2:  // 严重
        color = "#a94442"; bgColor = "#f2dede"; borderColor = "#ebccd1";
        break;
    default:
        color = "#31708f"; bgColor = "#d9edf7"; borderColor = "#bce8f1";
    }

    m_contentLabel->setStyleSheet(m_styleTemplate.arg(color, bgColor, borderColor));
}
